<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
	<el-card shadow="hover" class="layout-padding-auto create-form" >
		<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
			
<el-row :gutter="20">

<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_Name_FormItem" prop="Entity.Name"   :rules="[{ required: true, message:'名称为必填项',trigger:'blur'}]">
            <template #label>
                <WtmLabelTooltip label="名称" tooltip="物料名称" />
            </template>
        <el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_Code_FormItem" prop="Entity.Code"  >
            <template #label>
                <WtmLabelTooltip label="编码" tooltip="物料唯一编码，用于系统内标识物料" />
            </template>
        <el-input v-model="stateData.vmModel.Entity.Code" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_GroupCode_FormItem" prop="Entity.GroupCode" label="GroupCode" >
        <el-input v-model="stateData.vmModel.Entity.GroupCode" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_UnitCode_FormItem" prop="Entity.UnitCode" label="UnitCode" >
        <el-input v-model="stateData.vmModel.Entity.UnitCode" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_Model_FormItem" prop="Entity.Model" label="Model" >
        <el-input v-model="stateData.vmModel.Entity.Model" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
<el-col :xs="24" :lg="12" class="mb20">
    <el-form-item ref="Entity_Description_FormItem" prop="Entity.Description"  >
            <template #label>
                <WtmLabelTooltip label="详情" tooltip="物料详细描述信息" />
            </template>
        <el-input v-model="stateData.vmModel.Entity.Description" clearable class="width100"></el-input>
    </el-form-item>
</el-col>
</el-row>

		</el-form>
	</el-card>
	</div>
</template>


<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
	import ElMessage from 'element-plus/es/components/message/index';
	import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance} from 'vue';
	import { SysRawMaterialApi as api } from '/@/views/supplychain/sysrawmaterial/api';
	import other from '/@/utils/other';
	import { ISysRawMaterialVm } from '/@/views/supplychain/sysrawmaterial/api/interface';
	import { IViewModel } from '/@/types/common';
	
	

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
;


const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
;


const stateData = reactive<IViewModel<ISysRawMaterialVm>>({
	vmModel: {
		Entity:{
			Name: null,
			Code: null,
			GroupCode: null,
			UnitCode: null,
			Model: null,
			Description: null,
		},
		ActionName: null,
		IsMyApprove: null,

	},


});


const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});
;



const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};	
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
		},
		false
	);
};



// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
	]);
};


const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
;

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};


const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};</script>
